package i18n

import (
	current_scope "app/app_src/framework/security/current/scope"
	"fmt"

	"github.com/nicksnyder/go-i18n/v2/i18n"
	"golang.org/x/text/language"
)

const _DEFAULT_LANGUAGE_CODE = "zh-CN"
const _CURRENT_LANGUAGE_DATA_KEY = "i18n.current.language"
const _CURRENT_LOCALIZER_DATA_KEY = "i18n.current.localizer"

var _I18nBundle *i18n.Bundle

func init() {
	defaultLanguageTag := _ParseLanguageTag(_DEFAULT_LANGUAGE_CODE)
	_I18nBundle = i18n.NewBundle(defaultLanguageTag)
}

// 设置当前语言
func SetCurrentLanguage(langCode string) {
	current_scope.Set(_CURRENT_LANGUAGE_DATA_KEY, langCode)
}

func _ParseLanguageTag(langCode string) language.Tag {
	tags, _, err := language.ParseAcceptLanguage(langCode)
	if err != nil {
		panic(err)
	}

	return tags[0]
}

// 翻译文本
func T(msg string, args ...any) string {
	if len(args) == 0 {
		return msg
	}

	// 默认文本
	defaultMessage := i18n.Message{
		ID:    msg,
		Other: msg,
	}

	// 模板变量
	templateData := make(map[string]any, len(args))
	for index := range args {
		mapKey := fmt.Sprint("Arg", index)
		templateData[mapKey] = args[index]
	}

	var localizer *i18n.Localizer
	localizerAny := current_scope.Get(_CURRENT_LOCALIZER_DATA_KEY)

	if localizerAny == nil {
		localizer = i18n.NewLocalizer(_I18nBundle, GetLangCode())
		current_scope.Set(_CURRENT_LOCALIZER_DATA_KEY, localizer)
	} else {
		localizer = localizerAny.(*i18n.Localizer)
	}

	// 获取本地化文本
	localizedText, err := localizer.Localize(&i18n.LocalizeConfig{
		MessageID:      msg,
		DefaultMessage: &defaultMessage,
		TemplateData:   templateData,
	})

	// TODO 本地化出错不应该直接抛出异常
	if err != nil {
		panic(err)
	}

	return localizedText
}

// 获取语言代码
func GetLangCode() string {
	langCode := current_scope.Get(_CURRENT_LANGUAGE_DATA_KEY)

	if langCode != nil {
		return langCode.(string)
	}

	return _DEFAULT_LANGUAGE_CODE
}
